/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.integration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.message.Messenger;
import com.sinodata.bsm.center.service.probe.ProbeService;
import com.sinodata.bsm.center.service.resource.ResService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.RelationConstants;
import com.sinodata.bsm.common.constants.ResConstants;
import com.sinodata.bsm.common.message.ServiceMessage;
import com.sinodata.bsm.common.vo.Probe;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResAttrVal;
import com.sinodata.bsm.common.vo.ResType;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-7-28 下午5:12:54          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class TivoliAction extends BaseAction {

    private Long id;

    private Res entity;

    @Autowired
    private ResService resService;

    @Autowired
    private ResCache resCache;

    @Autowired
    private ProbeService probeService;

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private static final Logger logger = Logger.getLogger(TivoliAction.class);

    @SuppressWarnings("unchecked")
    public String guide() {
        List<Probe> probeList = probeService.findAllItipProbe();
        Collections.sort(probeList, new ProbeSort());
        request.setAttribute("viewId", request.getParameter("viewId"));
        request.setAttribute("probeList", probeList);
        return "guide";
    }

    /**
     * 跳转到Tivoli资源添加页面
     * @return
     */
    @Override
    public String input() {
        try {
            String id = request.getParameter("id");
            Res parent = resService.get(Long.parseLong(id));
            request.setAttribute("parent", parent);

            String probid = request.getParameter("probid");
            if (probid != null && probid.length() > 0) {
                Probe probe = probeService.findById(Long.parseLong(probid));
                request.setAttribute("probe", probe);
            }

            String resTypeId = request.getParameter("resTypeId");
            if (resTypeId != null && resTypeId.length() > 0) {
                ResType type = ResTypeBean.get(Long.parseLong(resTypeId)).resType();
                request.setAttribute("resType", type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "add";
    }

    /**
     * 得到可以集成的资源
     * @return
     */
    @SuppressWarnings("unchecked")
    public String itipAvailableRes() {

        String probeId = request.getParameter("probeId");
        String resType = request.getParameter("resType");

        JSONObject json = new JSONObject();

        try {
            ServiceMessage message = new ServiceMessage();
            message.setSrvId("ResFindService");
            message.setMethod("getTypeResList");
            message.setParams(new Object[] { resType });
            List<String[]> list = (List<String[]>) Messenger.getInstance().sendSyncMessage(Long.parseLong(probeId), message);
            if (list == null) {
                return null;
            }
            logger.info("接收到TIVOLI的资源" + list.size());
            JSONArray valid = new JSONArray();
            JSONArray invalid = new JSONArray();
            for (String[] sy : list) {
                if (sy[0] == null) {
                    continue;
                }
                JSONObject obj = new JSONObject();
                obj.element("name", sy[0].replace(" ", "&nbsp;"));
                if (testTrue(sy[0].split("--")[0])) {
                    valid.add(obj);
                } else {
                    invalid.add(obj);
                }
            }
            json.element("itip", "1");
            json.element("valid", valid);
            json.element("invalid", invalid);
            json.element("size", list.size());
        } catch (Exception e) {
            json.element("itip", "0");
            e.printStackTrace();
        }
        Struts2Utils.renderText(json.toString());
        return null;
    }

    private boolean testTrue(String str) {
        Res r = resCache.getResIdByIId(str);
        if (r == null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 批量添加资源
     * @return
     */
    public String batchAdd() {
        String parentId = request.getParameter("parent");
        String resType = request.getParameter("type");
        String probeId = request.getParameter("probeId");
        String names = request.getParameter("names");
        String[] tmp = names.split("___");
        logger.info(parentId + "  " + resType + "  " + probeId + "  " + names);

        JSONObject json = new JSONObject();
        List<ResAttrVal> attValList = new ArrayList<ResAttrVal>();
        try {
            for (String name : tmp) {
                Res res = new Res();
                res.setIp("127.0.0.1");
                //:KUX结尾 资源类别改成 目录
                if (name != null && name.matches(".*:KUX$")) {
                    res.setName(name.substring(0, name.length() - 4));
                    res.setInternalId(name.substring(0, name.length() - 4));
                    res.setCode(name.substring(0, name.length() - 4));
                    res.setResTypeId(1000000000000L);
                } else {//一般的资源  '#' 之前为资源的名称   之后为资源的描述  不是每个资源都有描述
                    String[] name_desc = name.split("--");
                    res.setName(name_desc[0]);
                    res.setInternalId(name_desc[0]);
                    res.setCode(name_desc[0]);
                    res.setResTypeId(Long.parseLong(resType));
                    if ("2104120000000".equals(resType)) {
                        res.setIp(name_desc[0]);
                    }
                    if (name_desc.length > 1) {
                        res.setDesc(name_desc[1]);
                    }
                }
                res.setHealthStatus(ResConstants.NORMAL_USABLE);
                res.setPaused(ResConstants.RES_NOT_PAUSED);
                res.setProbeId(Long.parseLong(probeId));

                resService.addResource(Long.parseLong(parentId), res, attValList, RelationConstants.SUPPORT);
            }

            /**
             * :KUX 结尾的改成树形的
             * 
             */
            for (String name : tmp) {
                if (name.matches(".*:KUX$")) {
                    //根据internalId 获取到父资源

                    String nameStr = name.substring(0, name.length() - 4);
                    Res pRes = resCache.getResIdByIId(nameStr);
                    if (pRes == null) {
                        continue;
                    }

                    //生成三个子资源::KUX  :PX  :KUL
                    Res res = new Res();
                    res.setName(name);
                    res.setInternalId(name);
                    res.setCode(name);
                    res.setResTypeId(Long.parseLong(resType));
                    res.setHealthStatus(ResConstants.NORMAL_USABLE);
                    res.setPaused(ResConstants.RES_NOT_PAUSED);
                    res.setProbeId(Long.parseLong(probeId));
                    res.setIp("127.0.0.1");
                    resService.addResource(pRes.getId(), res, attValList, RelationConstants.SUPPORT);

                    //
                    Res res1 = new Res();
                    res1.setName(nameStr + ":PX");
                    res1.setInternalId(nameStr + ":PX");
                    res1.setCode(nameStr + ":PX");
                    res1.setResTypeId(Long.parseLong(resType));
                    res1.setHealthStatus(ResConstants.NORMAL_USABLE);
                    res1.setPaused(ResConstants.RES_NOT_PAUSED);
                    res1.setProbeId(Long.parseLong(probeId));
                    res1.setIp("127.0.0.1");
                    resService.addResource(pRes.getId(), res1, attValList, RelationConstants.SUPPORT);

                    //
                    Res res2 = new Res();
                    res2.setName(nameStr + ":KUL");
                    res2.setInternalId(nameStr + ":KUL");
                    res2.setCode(nameStr + ":KUL");
                    res2.setResTypeId(Long.parseLong(resType));
                    res2.setHealthStatus(ResConstants.NORMAL_USABLE);
                    res2.setPaused(ResConstants.RES_NOT_PAUSED);
                    res2.setProbeId(Long.parseLong(probeId));
                    res2.setIp("127.0.0.1");
                    resService.addResource(pRes.getId(), res2, attValList, RelationConstants.SUPPORT);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.element("oper", "error");
        }

        json.element("oper", "success");
        Struts2Utils.renderJson(json);

        return null;
    }

    @Override
    public Object getModel() {
        return entity;
    }

    @Override
    public String list() throws Exception {
        return null;
    }

    @Override
    public String save() throws Exception {
        return null;
    }

    @Override
    public String delete() throws Exception {
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @SuppressWarnings("rawtypes")
    class ProbeSort implements Comparator {
        public int compare(Object obj1, Object obj2) {
            Probe res1 = (Probe) obj1;
            Probe res2 = (Probe) obj2;
            if (Math.abs(res1.getStatus() - 3) > Math.abs(res2.getStatus() - 3)) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    public static void main(String[] args) {
        //        String str = "abc \n deffasdf \rasdfdf";
        //        try {
        //            FileWriter fw = new FileWriter("E:\\file.txt");
        //            BufferedWriter bw = new BufferedWriter(fw);
        //            bw.write(str);
        //            bw.flush();
        //            bw.close();
        //            fw.close();
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        }

        String str = "172.17.3.11___H3C thisaas  ass";
        String[] tmp = str.split("[___]");
        System.out.println(tmp.length);
        System.out.println(tmp[0] + "---" + tmp[1]);
    }
}
